package com.mtiiot.mq.es;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by lcy on 16-6-22.
 */
public class ESClient {
    private static Logger logger = LogManager.getLogger(ESClient.class);

    public Client client = getClient("120.26.54.243");
    //public Client client = getClient("10.117.215.193");
    //public Client client = getClient("121.40.28.140");
    //创建客户端
    public Client getClient(String host) {
        try {
            Client client = TransportClient.builder().build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), 9300));


            return client;
        } catch (Exception ex) {
            logger.error(ex.getMessage(),ex);
        }
        return null;
    }

    public static void main(String[] args){
        ESClient esClient=new ESClient();
        Client client =esClient.client;
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("sysName", "ANALYZE");
        json.put("l1Name", "test");
        json.put("l2Name", "test");
        json.put("l3Name", "test");
        json.put("logLevel", "logic");
        json.put("keyValue", "test");
        json.put("message", "test");
        json.put("host", "test");
        json.put("postDate", new Date());

        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");//可以方便地修改日期格式
        IndexResponse response1 = client.prepareIndex("index-test", "type-test", "test_id_001")//参数说明： 索引，类型 ，_id
                //.setTimestamp(dateFormat1.format(new Date()))
                .setSource(json)//setSource可以传以上map string  byte[] 几种方式
                .get();
        boolean created = response1.isCreated();
        System.out.println("创建一条记录:" + created);

        if(true){
            return;
        }
//        //搜索
        String format="yyyy-MM-dd'T'HH:mm:ss.SSSZ";
        Date now=new Date();
        Date now_10 = new Date(now.getTime() - 1200000); //10分钟前的时间 10*60*1000
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);//可以方便地修改日期格式
        String startTime=dateFormat.format(now_10);
        String endTime=dateFormat.format(now);
        System.out.println(startTime);
        System.out.println(endTime);

        //June 22nd 2016, 17:16:01.010
        //MMM
        SearchResponse response = client.prepareSearch("log-*")//可以同时搜索多个索引prepareSearch("index","index2")
                //.setTypes("mapper")//可以同时搜索多个类型
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                //.setQuery(QueryBuilders.termQuery("logLevel", "error"))                 // Query
                //.setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
                .setPostFilter(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime))
                //.setFrom(0).setSize(2).setExplain(true)
                .execute()
                .actionGet();
        esClient.forSearchResponse(response);
        System.out.println("总共查询到有：" + response.getHits().getTotalHits());

    }

    public void forSearchResponse(SearchResponse response) {
        for (SearchHit hit1 : response.getHits()) {
            Map<String, Object> source1 = hit1.getSource();
            if (!source1.isEmpty()) {
                for (Iterator<Map.Entry<String, Object>> it = source1.entrySet().iterator(); it.hasNext(); ) {
                    Map.Entry<String, Object> entry = it.next();
                    System.out.println(entry.getKey() + "=======" + entry.getValue());
                }
            }
        }
    }




    /**
     * 将对象通过jackson.databind转换成byte[]
     * 注意一下date类型需要格式化处理  默认是 时间戳
     *
     * @return
     */
    public byte[] convertByteArray(Object obj) {
//        ObjectMapper mapper = new ObjectMapper(); // create once, reuse
//        try {
//            byte[] json = mapper.writeValueAsBytes(obj);
//            return json;
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
//        return null;
        return null;
    }

    /**
     * 将对象通过JSONtoString转换成JSON字符串
     * 使用fastjson 格式化注解  在属性上加入 @JSONField(format="yyyy-MM-dd HH:mm:ss")
     *
     * @return
     */
    public String jsonStr(Object obj) {
//        return JSON.toJSONString(obj);
        return null;
    }

    /**
     * 增删改查
     *
     * @throws Exception
     */
    public void test() throws Exception {
//        Map<String, Object> json = new HashMap<String, Object>();
//        json.put("name", "wangnian11");
//        json.put("postDate", new Date());
//        json.put("message", "trying out Elasticsearch");
//
//        User mapper = new User();
//        mapper.setId(2);
//        mapper.setName("更新第一条");
//        mapper.setPostDate(new Date());
//        mapper.setMessage("这是一个测试的数据");
//
//        IndexResponse response = client.prepareIndex("index", "mapper", mapper.getId().toString())//参数说明： 索引，类型 ，_id
//                .setSource(jsonStr(mapper))//setSource可以传以上map string  byte[] 几种方式
//                .get();
//        boolean created = response.isCreated();
//        System.out.println("创建一条记录:" + created);
//
//        //删除_id为1的类型
//        DeleteResponse response2 = client.prepareDelete("index", "mapper", "2").get();
//        System.out.println("删除一条数据：" + response2.isFound());
//
//        //更新
//        UpdateResponse updateResponse = client.prepareUpdate("index", "mapper", "1").setDoc(jsonBuilder()
//                .startObject()
//                .field("name", "王念")
//                .endObject())
//                .get();
//        System.out.println("更新一条数据:" + updateResponse.isCreated());
//
//
//        //获取_id为1的类型
//        GetResponse response1 = client.prepareGet("index", "mapper", "1").get();
//        response1.getSourceAsMap();//获取值转换成map
//        System.out.println("查询一条数据:" + JSON.toJSON(response1.getSourceAsMap()));
       // client.prepareG
    }


    public void test2() {
        //查询多个id的值
//        MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
//                .add("index", "mapper", "1")
//                .add("index", "mapper", "2", "3", "4")
//                .get();
//        for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
//            GetResponse response = itemResponse.getResponse();
//            if (response.isExists()) {
//                String json = response.getSourceAsString();
//                System.out.println(json);
//            }
//        }
//        //搜索
//        SearchResponse response = client.prepareSearch("index")//可以同时搜索多个索引prepareSearch("index","index2")
//                .setTypes("mapper")//可以同时搜索多个类型
//                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
//                .setQuery(QueryBuilders.termQuery("name", "张三"))                 // Query
//                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
//                .setFrom(0).setSize(2).setExplain(true)
//                .execute()
//                .actionGet();
//        forSearchResponse(response);
//        System.out.println("总共查询到有：" + response.getHits().getTotalHits());
//
//
//        //多查询结果
//        SearchRequestBuilder srb1 = client
//                .prepareSearch().setQuery(QueryBuilders.queryStringQuery("张三")).setSize(1);
//        SearchRequestBuilder srb2 = client
//                .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "张三")).setSize(1);
//
//        MultiSearchResponse sr = client.prepareMultiSearch()
//                .add(srb1)
//                .add(srb2)
//                .execute().actionGet();
//
//        long nbHits = 0;
//        for (MultiSearchResponse.Item item : sr.getResponses()) {
//            SearchResponse response1 = item.getResponse();
//            forSearchResponse(response1);
//            nbHits += response1.getHits().getTotalHits();
//        }
//        System.out.println("多查询总共查询到有：" + nbHits);
    }


}
